package com.example.financeapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.financeapi.config.constant.APIConstant;
import com.example.financeapi.config.annotation.PassToken;
import com.example.financeapi.config.wechat.mp.WxMpProperties;
import com.example.financeapi.entity.FUser;
import com.example.financeapi.service.FUserService;
import com.example.financeapi.utils.CookieUtil;
import com.example.financeapi.utils.HttpUtil;
import com.example.financeapi.utils.JWTUtils;
import com.example.financeapi.utils.RedisUtils;
import com.example.financeapi.entity.vo.ResultException;
import com.example.financeapi.entity.vo.ResultVOUtil;
import com.example.financeapi.entity.vo.ResultVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户表(FUser)表控制层
 * @author Alvin
 */
@RestController
@RequestMapping("fUser")
public class FUserController {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private WxMpProperties wxMpProperties;
    @Autowired
    private FUserService fUserService;

    /**
     * 登陆
     * @param openid
     * @return
     * @throws ResultException
     */
    @GetMapping("/login")
    public ResultVo login(@RequestParam("openid") String openid) throws ResultException {
        Map<String, Object> paramMap =new HashMap<>();
        paramMap.put("openid",openid);
        FUser getFUser = fUserService.getFUserByCode(paramMap);
        if(getFUser ==null){
            return ResultVOUtil.error("【login 接口】用户登陆失败！");
        }
        //设置token至redis和Cookie
        String token = JWTUtils.createJWT(getFUser.getId()+"", APIConstant.JWT_TOKEN_TIMES);
        redisUtils.set(getFUser.getId()+"",getFUser.getUnionid(), APIConstant.TOKEN_TIMES);
        return ResultVOUtil.success(token);
    }

    /**
     * 登出 TODO
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/logout")
    public ResultVo logout(HttpServletRequest request, HttpServletResponse response) {
        //1. 从cookie里查询
        Cookie cookie = CookieUtil.get(request, APIConstant.COOKIE_TOKEN_PREFIX);
        if (cookie != null) {
            //2. 清除redis
            redisUtils.del(cookie.getValue());
            //3. 清除cookie
            CookieUtil.set(response, APIConstant.COOKIE_TOKEN_PREFIX, null, 0);
        }
        return ResultVOUtil.success();
    }

    /**
     * 公众号获取unionid
     * @param openid
     * @return
     */
    @PassToken
    @RequestMapping("getUnionID")
    public ResultVo getUnionID(String openid) {
        String unionID ="";
        String getAccessToken ="";
        try {
            String getMyAppId =wxMpProperties.getConfigs().get(0).getAppId();
            String getMyAppSecret =wxMpProperties.getConfigs().get(0).getSecret();
            getAccessToken =redisUtils.get("mp_access_token-"+getMyAppId);
            if(StringUtils.isEmpty(getAccessToken)){
                //获取token
                String getTokenApi = String.format(APIConstant.MX_ACCESS_TOKEN_URL,getMyAppId,getMyAppSecret);
                String tokenJsonStr = HttpUtil.doGetPost(getTokenApi,"GET",null);
                JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
                getAccessToken = (String) tokenJson.get("access_token");
                redisUtils.set("mp_access_token-"+getMyAppId,getAccessToken, APIConstant.TOKEN_TIMES);
            }
            //获取unionid
            String getUnionIDApi = String.format(APIConstant.GET_MP_UNIONID_URL,getAccessToken,openid);
            String JsonStr = HttpUtil.doGetPost(getUnionIDApi,"GET",null);
            JSONObject jsonObj = JSONObject.parseObject(JsonStr);
            if("1".equals(jsonObj.get("subscribe")+"")){
                unionID= (String) jsonObj.get("unionid");
            }else{
                return ResultVOUtil.error(jsonObj);
            }
        }catch (Exception e){
            throw new RuntimeException(e.getMessage(),e);
        }
        return ResultVOUtil.success(unionID);
    }

}